using System;
using System.ComponentModel;
using DevExpress.ExpressApp;
using DevExpress.ExpressApp.Xpo;
using DevExpress.ExpressApp.Win;
using System.Collections.Generic;
using DevExpress.ExpressApp.Updating;
using System.Threading;
using DevExpress.Xpo;
using DevExpress.Persistent.BaseImpl;
using System.Data.SqlClient;
using System.Data;
using System.Net;
using L4Alive.Module.Controllers;
//using DevExpress.ExpressApp.Security;

namespace L4Alive.Win
{
    // For more typical usage scenarios, be sure to check out http://documentation.devexpress.com/#Xaf/DevExpressExpressAppWinWinApplicationMembersTopicAll
    public partial class L4AliveWindowsFormsApplication : WinApplication
    {
        /// <summary>
        /// vlakno na loggin
        /// </summary>
        Thread thread_logg;

        public override void LogOff()
        {
            base.LogOff();

        }

        /// <summary>
        /// pri odhlaseni
        /// </summary>
        /// <remarks>
        /// ...
        /// </remarks>
        /// <param name="args"></param>
        protected override void OnLoggingOff(LoggingOffEventArgs args)
        {
            try
            {
                base.OnLoggingOff(args);
                IObjectSpace OS = this.ObjectSpaceProvider.CreateObjectSpace();

                Session xafSess = ((XPObjectSpace)OS).Session;

                //kilnu si thread na aktualizaci logging
                if (thread_logg != null)
                {
                    thread_logg.Abort();
                }
                // udelam odhlaseni - ukonceni APP
                OnLoggedOffThread(((XPObjectSpace)OS).Session.ConnectionString, customAuthentication1.ID_L4_UTIL_APP_RUNNING.ID_L4_UTIL_APP_RUNNING);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        /// <summary>
        /// pri prihlaseni
        /// 
        /// </summary>
        /// <param name="args"></param>
        /// <remarks>
        /// ...
        /// 
        /// </remarks>
        protected override void OnLoggedOn(LogonEventArgs args)
        {
            base.OnLoggedOn(args);


            IObjectSpace OS = this.ObjectSpaceProvider.CreateObjectSpace();


            //zavolam si vlakno na loggin 
            //if (!L4_UzPravo.OverUzPravo(((XPObjectSpace)OS).Session, 106))
            //{
            IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());

            User l4user = ((XPObjectSpace)OS).Session.GetObjectByKey<User>(((XPObjectSpace)OS).Session.GetKeyValue(SecuritySystem.CurrentUser));

            ThreadStart thread_loggedOn = delegate
            {
                OnLoggedOnThread(((XPObjectSpace)OS).Session.ConnectionString, l4user, System.Environment.MachineName, host.AddressList[host.AddressList.Length - 1].ToString(), System.Environment.UserName, customAuthentication1.ID_L4_UTIL_APP_RUNNING.ID_L4_UTIL_APP_RUNNING);
            };
            thread_logg = new Thread(thread_loggedOn);
            thread_logg.Start();
            //}
        }



        /// <summary>
        /// vlakno na aktualizace logged -
        /// </summary>
        /// <remarks>
        /// ...
        /// 19.12.2013 SL;
        /// 7.1.2013 SL; predelano bez ulozene procedury 
        /// </remarks>
        public void OnLoggedOnThread(string sConnectionString, User l4user, string sMachineName, string sIPadress, string sUserNameOS, int id_l4_util_app_running)
        {
            try
            {
                int iMinutes = 30000;

                //if (System.Configuration.ConfigurationManager.AppSettings["DELAY_APP_RUNING"] == null ||
                //      System.Configuration.ConfigurationManager.AppSettings["DELAY_APP_RUNING"].ToString() == "")
                //    iMinutes = 600000;
                //else
                //    iMinutes = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["DELAY_APP_RUNING"]) * 60000;


                while (true)
                {
                    Thread.Sleep(iMinutes);
                    //                    KontrolaConnection(ref myConnection);

                    try
                    {
                        using (SqlConnection myConnection = new SqlConnection(sConnectionString))
                        {
                            myConnection.Open();

                            //SqlCommand myCommand = new SqlCommand("L4_UTIL_APP_RUNNING_Actual", myConnection);
                            SqlCommand myCommand = new SqlCommand("update L4_UTIL_APP_RUNNING set DT_APP_RUNNING=GETDATE() where ID_L4_UTIL_APP_RUNNING=@id_l4_util_app_running", myConnection);
                            myCommand.Parameters.AddWithValue("@id_l4_util_app_running", id_l4_util_app_running);
                            myCommand.CommandType = CommandType.Text;
                            myCommand.ExecuteNonQuery();

                            myConnection.Close();
                        }
                    }
                    catch (Exception)
                    {
                    }
                }
            }
            catch (Exception ex)
            {

            }
        }

        /// <summary>
        /// vlakno na aktualizace logged - pouyiva sp L4_UTIL_APP_RUNNING_LogOff
        /// </summary>
        /// <remarks>
        /// ...
        /// 19.12.2013 SL;
        /// 7.1.2014 SL; predelano bez ulozene procedury
        /// </remarks>
        public void OnLoggedOffThread(string sConnectionString, int id_l4_util_app_running)
        {
            try
            {
                using (SqlConnection myConnection = new SqlConnection(sConnectionString))
                {
                    myConnection.Open();

                    //SqlCommand myCommand = new SqlCommand("L4_UTIL_APP_RUNNING_LogOff", myConnection);
                    SqlCommand myCommand = new SqlCommand("update L4_UTIL_APP_RUNNING set DT_ODHLASENI=GETDATE(),JE_PRIHLASEN=0  where ID_L4_UTIL_APP_RUNNING=@id_l4_util_app_running", myConnection);
                    myCommand.Parameters.AddWithValue("@id_l4_util_app_running", id_l4_util_app_running);
                    myCommand.CommandType = CommandType.Text;
                    myCommand.ExecuteNonQuery();
                }
            }
            catch (Exception)
            {
            }
        }

        public L4AliveWindowsFormsApplication()
        {
            InitializeComponent();
        }

        protected override void CreateDefaultObjectSpaceProvider(CreateCustomObjectSpaceProviderEventArgs args)
        {
            args.ObjectSpaceProvider = new XPObjectSpaceProvider(args.ConnectionString, args.Connection);
        }

        protected override IObjectSpace CreateLogonWindowObjectSpace(
 object logonParameters)
        {
            return ((CustomLogonParameters)logonParameters).ObjectSpace =
                this.CreateObjectSpace(); ;
        }

        private void L4AliveWindowsFormsApplication_CustomizeLanguagesList(object sender, CustomizeLanguagesListEventArgs e)
        {
            string userLanguageName = System.Threading.Thread.CurrentThread.CurrentUICulture.Name;
            if (userLanguageName != "en-US" && e.Languages.IndexOf(userLanguageName) == -1)
            {
                e.Languages.Add(userLanguageName);
            }
        }
        private void L4AliveWindowsFormsApplication_DatabaseVersionMismatch(object sender, DevExpress.ExpressApp.DatabaseVersionMismatchEventArgs e)
        {
#if EASYTEST
            e.Updater.Update();
            e.Handled = true;
#else
            if (System.Diagnostics.Debugger.IsAttached)
            {
                e.Updater.Update();
                e.Handled = true;
            }
            else
            {
                throw new InvalidOperationException(
                    "The application cannot connect to the specified database, because the latter doesn't exist or its version is older than that of the application.\r\n" +
                    "This error occurred  because the automatic database update was disabled when the application was started without debugging.\r\n" +
                    "To avoid this error, you should either start the application under Visual Studio in debug mode, or modify the " +
                    "source code of the 'DatabaseVersionMismatch' event handler to enable automatic database update, " +
                    "or manually create a database using the 'DBUpdater' tool.\r\n" +
                    "Anyway, refer to the 'Update Application and Database Versions' help topic at http://www.devexpress.com/Help/?document=ExpressApp/CustomDocument2795.htm " +
                    "for more detailed information. If this doesn't help, please contact our Support Team at http://www.devexpress.com/Support/Center/");
            }
#endif
        }
    }
}
